package gui;

import database.DatabaseWorker;
import database.entity.User;
import gui.component.image.ResourceLoader;
import java.awt.Color;
import java.io.IOException;
import java.util.LinkedList;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author Tom
 */
public class UILogin extends javax.swing.JFrame {

    public UILogin() 
    {       
        
        initComponents();
        initInterface();        
        this.pack();
        this.setLocationRelativeTo(null);
        
        //check some conditions
        checkDB();    
        
    }
    
    private void initInterface() 
    {
        lbImage.setIcon(new ImageIcon(ResourceLoader.class.getResource("thunderpig.png")));
    }
     
    private void checkDB()
    {
        //check database
        if (!DatabaseWorker.checkDB())
        {
            JOptionPane.showMessageDialog(this, "Mailer ne peut pas accéder à la base de données!", "ERREUR FATALE", JOptionPane.ERROR_MESSAGE);
            System.exit(2);
        }
        loadEmail();
       
    }
    
    public void loadEmail()
    {
        cboxEmail.removeAllItems();
        LinkedList<String> emails = DatabaseWorker.getUserEmails();
        emails.stream().forEach((email) ->
        {
            cboxEmail.addItem(email);
        });
        if (emails.size()==0)
        {
            cboxEmail.setEnabled(false);
            txtPassword.setEnabled(false);
            lbRegister.setForeground(Color.RED);
            btLogin.setEnabled(false);
        }
        else
        {
            cboxEmail.setEnabled(true);
            btLogin.setEnabled(true);
            txtPassword.setEnabled(true);
        }              
    }
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cboxEmail = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        btLogin = new javax.swing.JButton();
        lbRegister = new javax.swing.JLabel();
        lbImage = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ThunderPig ®");
        setResizable(false);
        setType(java.awt.Window.Type.UTILITY);

        cboxEmail.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cboxEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboxEmailActionPerformed(evt);
            }
        });

        jLabel1.setText("Email");

        jLabel2.setText("Mot de passe");

        txtPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPasswordActionPerformed(evt);
            }
        });

        btLogin.setText("Se connecter ");
        btLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btLoginActionPerformed(evt);
            }
        });

        lbRegister.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lbRegister.setText("Inscrivez-vous!");
        lbRegister.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        lbRegister.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lbRegisterMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                lbRegisterMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                lbRegisterMouseExited(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lbImage, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(13, 13, 13))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(cboxEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap()))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(lbRegister)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap()))
                    .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lbImage, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cboxEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lbRegister))))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btLoginActionPerformed
        try 
        {
            String password  = new String(txtPassword.getPassword());
            
            if ("".equals(password))
            {
                JOptionPane.showMessageDialog(this, "Veuillez saisir votre mot de passe!", "", JOptionPane.INFORMATION_MESSAGE);
                txtPassword.requestFocus();
            }
            else
            {
                //login return UserID
                User loginResult = DatabaseWorker.checkLogin(cboxEmail.getSelectedItem().toString(), password);
                if (loginResult==null)
                {
                    JOptionPane.showMessageDialog(this, "Mot de passe invalide!", "", JOptionPane.ERROR_MESSAGE);
                    txtPassword.setText("");
                    txtPassword.requestFocus();
                }
                else
                {
                    this.setVisible(false);
                    UIMain e = new UIMain(loginResult);
                    e.setVisible(true);
                    this.dispose();
                }
            }
        } 
        catch (IOException ex) 
        {
            JOptionPane.showMessageDialog(this, "Erreur criticale se produit!", "", JOptionPane.INFORMATION_MESSAGE);
            //exit with code 2: database IO problem
            System.exit(2);
        }
    }//GEN-LAST:event_btLoginActionPerformed

    private void lbRegisterMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbRegisterMouseEntered
        lbRegister.setForeground(Color.BLUE);
    }//GEN-LAST:event_lbRegisterMouseEntered

    private void lbRegisterMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbRegisterMouseExited
        if (txtPassword.isEnabled())
        {
            lbRegister.setForeground(Color.BLACK);
        }
        else
        {
            lbRegister.setForeground(Color.RED);
        }
    }//GEN-LAST:event_lbRegisterMouseExited

    private void lbRegisterMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lbRegisterMouseClicked
        this.setVisible(false);
        UIRegister reg = new UIRegister();        
        reg.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_lbRegisterMouseClicked

    private void cboxEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboxEmailActionPerformed
        if (txtPassword.isEnabled())
        {
            txtPassword.requestFocus();
        }
    }//GEN-LAST:event_cboxEmailActionPerformed

    private void txtPasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordActionPerformed
        btLoginActionPerformed(evt);
    }//GEN-LAST:event_txtPasswordActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btLogin;
    private javax.swing.JComboBox cboxEmail;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel lbImage;
    private javax.swing.JLabel lbRegister;
    private javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables
}
